package com.flower.oauth2.service.Impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.flower.oauth2.entity.SysPermission;
import com.flower.oauth2.entity.SysRole;
import com.flower.oauth2.entity.SysUser;
import com.flower.oauth2.mapper.SysUserMapper;
import com.flower.oauth2.service.SysUserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @ClassName SysUserServiceImpl
 * @Descrtption 用户业务实现类
 * @Date 2021/08/23
 * @Author wuhanxiong
 */

@Service
public class SysUserServiceImpl implements UserDetailsService, SysUserService {

    private static Logger logger = Logger.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Collection<SimpleGrantedAuthority> authorities  = new ArrayList<>();
        SysUser sysUser = null;
        if(StringUtils.isNotBlank(username)){
            sysUser = sysUserMapper.getSingleUser(username);
            if(sysUser == null){
                logger.error("用户不存在");
                throw new AuthenticationCredentialsNotFoundException("用户不存在");
            }

        }
        List<SysRole> roleList = sysUser.getRoles();
        roleList.stream().forEach(role -> {
            List<SysPermission> sysPermissionList = role.getPermissions();
            sysPermissionList.stream().forEach(permission -> {
                authorities.add(new SimpleGrantedAuthority(permission.getAuthIden()));
            });
        });
        UserDetails userDetails = null;
        try {
             userDetails = new User(sysUser.getUsername(), sysUser.getPassword(),
                    authorities);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("测试-----------------------");
        }
        return userDetails;
    }


    @Override
    public SysUser getSingleUser(String username) {
        return sysUserMapper.getSingleUser(username);
    }
}
